package com.example.cadmin.utils.Netty;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.cadmin.entity.Host;
import com.example.cadmin.service.HostService;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 发送命令封装工具类
 */
@Slf4j
@Component
public class sendCmd {
    @Resource
    public HostService hostService;

    public void send(String cmdName, HttpServletRequest request, String appointIp) {
        String sendIpAddress = "";
        if (request != null) {
            HttpSession session = request.getSession();
            sendIpAddress = Convert.toStr(session.getAttribute("cabinet"));
        } else {
            sendIpAddress = appointIp;
        }
        if (NettyServerHandler.channelGroup.size() == 0) {
            hostService.update(new UpdateWrapper<Host>().set("connection_status", 0));
            log.info("设备全部离线");
        }

        String finalSendIpAddress = sendIpAddress;
        NettyServerHandler.channelGroup.forEach(channel -> {
            System.out.println(channel.remoteAddress());
            if (finalSendIpAddress.equals(channel.remoteAddress().toString().split(":")[0].replace("/", ""))) {
                try {
                    System.out.println("已发送  " + "主机ip是  " + finalSendIpAddress + "命令为 " + cmdName + "\r\n");
                    channel.writeAndFlush(Unpooled.buffer().writeBytes((cmdName + "\r\n").getBytes("gbk")));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("未发送");
            }
        });
    }
}
